package blog

import (
	"gitee.com/lishixi/gops/vblog/apps/blog"
	"gitee.com/lishixi/gops/vblog/middleware"
	"github.com/gin-gonic/gin"
	"github.com/infraboard/mcube/v2/http/gin/response"
	"github.com/infraboard/mcube/v2/ioc"

	// 引入Gin Root Router: *gin.Engine
	ioc_gin "github.com/infraboard/mcube/v2/ioc/config/gin"
)

func init() {
	ioc.Api().Registry(&BlogApiHandler{})
}

type BlogApiHandler struct {
	ioc.ObjectImpl
	blog blog.Service
}

func (h *BlogApiHandler) Name() string {
	return "blogs"
}

func (h *BlogApiHandler) Init() error {
	h.blog = blog.GetService()

	r := ioc_gin.ObjectRouter(h)
	r.GET("", h.QueryBlog)

	r.Use(middleware.Auth)
	r.POST("", h.CreateBlog)
	return nil

}

// func (h *BlogApiHandler) Register(r *gin.Engine) {
// 	router := r.Group("/vblog/api/v1/blogs")
// 	router.GET("", h.QueryBlog)
// 	router.Use(middleware.Auth)
// 	router.POST("", h.CreateBlog)
// }

func (h *BlogApiHandler) CreateBlog(ctx *gin.Context) {
	in := &blog.CreateBlogRequest{}
	if err := ctx.BindJSON(in); err != nil {
		response.Failed(ctx, err)
		return
	}
	ins, err := h.blog.CreateBlog(ctx.Request.Context(), in)
	if err != nil {
		response.Failed(ctx, err)
		return
	}
	response.Success(ctx, ins)
}

func (h *BlogApiHandler) QueryBlog(ctx *gin.Context) {
	in := blog.NewQueryBlogRequest()
	if err := ctx.BindQuery(in); err != nil {
		response.Failed(ctx, err)
		return
	}
	in.SetTag(ctx.Query("tag"))
	h.blog.QueryBlog(ctx.Request.Context(), in)
	ins, err := h.blog.QueryBlog(ctx.Request.Context(), in)
	if err != nil {
		response.Failed(ctx, err)
		return
	}
	response.Success(ctx, ins)

}
